<!DOCTYPE html>
<html>
<head>
	<title>删除链表的倒数第n个节点</title>
</head>
<body>
<script>
	function LinkedList () {
	function Node (element) {
		this.element = element;// 存放节点内容
		this.next = null;//下一个的指针
	}
	let head = null,
		length = 0;

	this.append = function (element) {
		let node = new Node(element),
			current;

		if(!head) {
			head = node;
		}else {
			current = head;
			while(current.next) {
				current = current.next;
			}
			current.next = node;
		}

		length++;
		return true;
	}
	this.toString = function () {
		let str = '',
			current = head; 

		while(current) {
			str += current.element;
			current = current.next;
		}

		return str;
	}
	this.getHead = function () {
		return head;
	}
}
var linkedList1 = new LinkedList();
linkedList1.append(11);
linkedList1.append(12);
linkedList1.append(13);
linkedList1.append(14);
linkedList1.append(15);
linkedList1.append(16);
linkedList1.append(17);
/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
 
/**
  *
  * @param head ListNode类
  * @param n int整型
  * @return ListNode类
  */
function removeNthFromEnd(head, n) {
	let len = 1;
	let totalH = head, p = head;
	// 先遍历出链表总长度 len
	while(totalH.next) {
		totalH = totalH.next;
		len++;
	}
	let i = len - n;//head遍历时要删除的节点位置
	// 第一个节点
	if(i == 0) {
		return p.next;
	}

	while(i > 1) {
		p = p.next;
		i--;
	}
	// 要删除的节点就是p.next
	// 不能用 p=p.next,这样只是重新给p赋值
	p.next = p.next.next;

	return head;
}
console.log(removeNthFromEnd(linkedList1.getHead(), 6));
</script>
</body>
</html>